package com.vhly.ddxdecompiler.dexreader.file.mixeditem;

import com.vhly.ddxdecompiler.dexreader.file.DexFile;
import com.vhly.ddxdecompiler.dexreader.file.MethodIdsSection;
import com.vhly.ddxdecompiler.dexreader.io.DexInputStream;

import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;

/**
 * Created by IntelliJ IDEA.
 * User: vhly
 * Date: 2009-10-21
 * Time: 10:24:29
 *
 * @author vhly[FR]
 */
public class EncodeMethod implements EncodeMember {

    private DexFile dex;

    int diff;
    int methodIdIndex;
    int accessFlags;
    int codeOff;

    MethodIdItem method;

    CodeItem code;

    public EncodeMethod(DexFile dexFile) {
        dex = dexFile;
    }

    /**
     * 读取编码后的数据
     *
     * @param din 数据流
     * @throws java.io.IOException 异常
     */
    public void readEncode(DexInputStream din) throws IOException {
        diff = din.readUnsignedLeb128();
        accessFlags = din.readUnsignedLeb128();
        codeOff = din.readUnsignedLeb128();
    }

    /**
     * 重新定位
     *
     * @param bin    数据流
     * @param offset 起始偏移
     * @throws java.io.IOException 异常
     */
    public void reloc(ByteArrayInputStream bin, int offset) throws IOException {
        // TODO this method must call after readEncode finish and calced index value.
        MethodIdsSection methodIds = dex.getMethodIds();
        method = methodIds.indexOf(methodIdIndex);
        String mn = method.nameItem.getDataItem().value;
        System.out.println("[Debug] Method " + mn);
        int off = codeOff;
        if (off > 0) {
            bin.reset();
            code = new CodeItem(dex);
            DataInputStream din = new DataInputStream(bin);
            DexInputStream dxin = new DexInputStream(din, 1);
            bin.skip(off - offset);
            dxin.setOffset(off);
            code.read(dxin);
            dxin.close();
            din.close();
        }
    }
}
